package cn.krund.lyc.hotlerobot.wifimanage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Parcelable;

import java.net.Inet4Address;
import java.util.List;

/**
 * @包名: cn.krund.lyc.hotlerobot.wifimanage
 * @作者: 刘育成
 * @时间: 2018/3/27  11:17
 * @org: 克路德人工智能
 * @描述: TODO
 * @fileName: WifiAdmin
 */
public class WifiAdmin extends BroadcastReceiver {

    //定义WiFimanager对象
    private WifiManager mWifiManager;

    private WifiInfo mWifiInfo;                                      // 定义wifiInfo对象

    private List<ScanResult> mWifiList;                             // 扫描到的网络连接列表.

    private List<WifiConfiguration> mWifiConfiguration;            // 网络连接列表

    private OnNetworkChangeListener onNetworkChangeListener;


    //得到网络列表
    public List<ScanResult> getWifiList() {
        return mWifiList;
    }

    public OnNetworkChangeListener getOnNetworkChangeListener() {
        return onNetworkChangeListener;
    }

    public void setOnNetworkChangeListener(OnNetworkChangeListener noNetworkChangeListener) {
        this.onNetworkChangeListener = noNetworkChangeListener;
    }

    public void setmWifiConfiguration(List<WifiConfiguration> mWifiConfiguration) {
        this.mWifiConfiguration = mWifiConfiguration;
    }

    public void WifiAdminInit(Context context){
//        m_count++;
//        wifiList.add(this);

        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        context.registerReceiver(this, filter);
    }

    public void Dispose(Context context){
        //取消注册广播
//        context.unregisterReceiver(this);
    }

    // 定义一个WifiLock
    WifiManager.WifiLock mWifiLock;
    public WifiAdmin(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        context.registerReceiver(this, filter);
        //取得wifimanager对象
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        //取得wifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    //检查当前wifi状态
    public int checkState() {
        return mWifiManager.getWifiState();
    }
    //wifi当前状态
    public boolean getWifiState() {
        return mWifiManager.isWifiEnabled();
    }
    // 打开WIFI
    public boolean openWifi() {
        boolean bRet = true;
        if (!mWifiManager.isWifiEnabled()) {
            bRet = mWifiManager.setWifiEnabled(true);
        }
        return bRet;
    }

    //关闭wifi
    public boolean closeWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            return true;
        } else {
            return mWifiManager.setWifiEnabled(false);
        }
    }

    //创建wifi锁
    public void creatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("test");// 创建一个锁的标志

    }

    //锁定/解锁wifi
    // 其实锁定WiFI就是判断wifi是否建立成功，在这里使用的是held，握手的意思acquire 得到！
    public void lockWifi() {
        mWifiLock.acquire();
    }

    public void unLockWifi() {
        if (!mWifiLock.isHeld()) {
            mWifiLock.release();//释放资源
        }
    }
    //得到配置好的网络
    public List<WifiConfiguration> getWifiConfiguration() {
        return mWifiConfiguration;
    }

    //指定配置好的网络进行连接
    public void connetionConfiguration(int index) {
        if (index > mWifiConfiguration.size()) {
            return;
        }
        //连接配置好指定ID的网络
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
    }

    //扫描网络
    public void startScan() {
        mWifiManager.startScan();
        //得到扫描结果
        mWifiList = mWifiManager.getScanResults();
        for (int i = 0; i < mWifiList.size()-1; i++) {
            for (int j = mWifiList.size()-1; j > i; j--) {
                if (mWifiList.get(j).SSID.equals(mWifiList.get(i).SSID)) {
                    mWifiList.remove(j);
                }
            }
        }
        //得到配置好的网络连接
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    }

    //查看扫描结果
    public StringBuffer lookUpScan() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0;i < mWifiList.size();i++) {
            sb.append("Index_" + new Integer(i + 1).toString() + ":");
            // 将ScanResult信息转换成一个字符串包
            // 其中把包括：BSSID、SSID、capabilities、frequency、level
            sb.append((mWifiList.get(i)).toString()).append("\n");
        }
        return sb;
    }
    //获取mac地址
    public String getMacAddress() {
        return (mWifiInfo == null) ? "null" : mWifiInfo.getMacAddress();
    }

    public String getBSSID() {
        return (mWifiInfo == null) ? "null" : mWifiInfo.getBSSID();
    }

    public int  getIpAddress() {
        return (mWifiInfo == null) ?  0: mWifiInfo.getIpAddress();
    }
    public int getNetWordId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    //得到wifi所有信息
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }
    //添加一个网络并连接
    public void addNetWork(WifiConfiguration configuration) {
        int wcgId = mWifiManager.addNetwork(configuration);
        mWifiManager.enableNetwork(wcgId, true);
    }

    //断开指定ID网络
    public void disConnectionWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }
    public static boolean isWifiConnect(Context context){

        ConnectivityManager connManager =
                (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }

    /**
     * /提供一个外部接口，传入要连接的无线网
     * 没密码：{WIFICIPHER_NOPASS}
     * WEP加密： {WIFICIPHER_WEP}
     * WPA加密： {WIFICIPHER_WPA}
     *
     * @return true:连接成功；false:连接失败<br>
     */

    public boolean connect(String SSID, String Password, String Type) {
        if (!this.openWifi()) {
            return false;
        }
        // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
        while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
            try {
                // 为了避免程序一直while循环，让它睡个100毫秒在检测……
                Thread.currentThread();
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
        }
        WifiConfiguration wifiConfig = createWifiInfo(SSID, Password, Type);
        //
        if (wifiConfig == null) {
            return false;
        }
        WifiConfiguration tempConfig = this.isExsits(SSID);
        int tempId = wifiConfig.networkId;
        if (tempConfig != null) {
            tempId = tempConfig.networkId;
            mWifiManager.removeNetwork(tempConfig.networkId);
        }
        int netID = mWifiManager.addNetwork(wifiConfig);
        // 断开连接
        mWifiManager.disconnect();
        // 重新连接
        //netID = wifiConfig.networkId;
        // 设置为true,使其他的连接断开
        boolean isConn = mWifiManager.enableNetwork(netID, true);
        mWifiManager.reconnect();
        return isConn;
    }
    // 查看以前是否也配置过这个网络
    private WifiConfiguration isExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = mWifiManager
                .getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }
    private WifiConfiguration createWifiInfo(String SSID, String Password, String Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        //无密码
        if (Type.equals("NOPASS")) {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        //wep
        if (Type.equals("WEP")) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        //wpa
        if (Type.equals("WPA")) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            return null;
        }
        return config;
    }
    private boolean isConnect;
    //判断扫描结果是否连接上
    public boolean isCoonnct(ScanResult result) {
        if (result == null) {
            isConnect=false;
            return false;
        }
        mWifiInfo = mWifiManager.getConnectionInfo();
        String str = "\"" + result.SSID + "\"";
        if (mWifiInfo.getSSID() != null && mWifiInfo.getSSID().endsWith(str)&& getIpAddress()!=0) {
            isConnect=true;
            return true;
        }
        isConnect=false;
        return false;
    }



    /**将int类型的IP转换成字符串形式的IP
     * @param ip
     * @return
     */
    public String ipIntToString(int ip) {
        try {
            byte[] bytes = new byte[4];
            bytes[0] = (byte) (0xff & ip);
            bytes[1] = (byte) ((0xff00 & ip) >> 8);
            bytes[2] = (byte) ((0xff0000 & ip) >> 16);
            bytes[3] = (byte) ((0xff000000 & ip) >> 24);
            return Inet4Address.getByAddress(bytes).getHostAddress();
        } catch (Exception e) {
            return "";
        }
    }
    public int getConnNetId() {
        // result.SSID;
        mWifiInfo = mWifiManager.getConnectionInfo();
        return mWifiInfo.getNetworkId();
    }


    /**
     * 信号强度转换为字符串
     * @param level
     * @return
     */
    public static String singlLevToStr(int level) {

        String resuString = "无信号";

        if (Math.abs(level) > 100) {
        } else if (Math.abs(level) > 80) {
            resuString = "弱";
        } else if (Math.abs(level) > 70) {
            resuString = "强";
        } else if (Math.abs(level) > 60) {
            resuString = "强";
        } else if (Math.abs(level) > 50) {
            resuString = "较强";
        } else {
            resuString = "极强";
        }
        return resuString;
    }
    /**
     * 添加到网络
     * @param wcg
     */
    public boolean addNetwork(WifiConfiguration wcg) {
        if (wcg == null) {
            return false;
        }
        //receiverDhcp = new ReceiverDhcp(ctx, mWifiManager, this, wlanHandler);
        //ctx.registerReceiver(receiverDhcp, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
        int wcgID = mWifiManager.addNetwork(wcg);
        boolean b = mWifiManager.enableNetwork(wcgID, true);
        mWifiManager.saveConfiguration();
        System.out.println(b);
        return b;
    }

    public boolean connectSpecificAP(ScanResult scan) {
        List<WifiConfiguration> list = mWifiManager.getConfiguredNetworks();
        boolean networkInSupplicant = false;
        boolean connectResult = false;
        // 重新连接指定AP
        mWifiManager.disconnect();
        for (WifiConfiguration w : list) {
            // 将指定AP 名字转化
            // String str = convertToQuotedString(info.ssid);
            if (w.BSSID != null && w.BSSID.equals(scan.BSSID)) {
                connectResult = mWifiManager.enableNetwork(w.networkId, true);
                // mWifiManager.saveConfiguration();
                networkInSupplicant = true;
                break;
            }
        }
        if (!networkInSupplicant) {
            WifiConfiguration config =  CreateWifiInfo(scan, "");
            connectResult = addNetwork(config);
        }

        return connectResult;
    }

    public WifiConfiguration CreateWifiInfo(ScanResult scan, String Password) {
        // Password="ultrapower2013";
        // deleteExsits(info.ssid);
        WifiConfiguration config = new WifiConfiguration();
        config.hiddenSSID = false;
        config.status = WifiConfiguration.Status.ENABLED;

        if (scan.capabilities.contains("WEP")) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP104);

            config.SSID = "\"" + scan.SSID + "\"";

            config.wepTxKeyIndex = 0;
            config.wepKeys[0] = Password;
            // config.preSharedKey = "\"" + SHARED_KEY + "\"";
        } else if (scan.capabilities.contains("PSK")) {
            //
            config.SSID = "\"" + scan.SSID + "\"";
            config.preSharedKey = "\"" + Password + "\"";
        } else if (scan.capabilities.contains("EAP")) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.SSID = "\"" + scan.SSID + "\"";
            config.preSharedKey = "\"" + Password + "\"";
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

            config.SSID = "\"" + scan.SSID + "\"";
            // config.BSSID = info.mac;
            config.preSharedKey = null;
            //
        }

        return config;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (this.getOnNetworkChangeListener() != null) {
            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                System.out.println("网络状态改变");
//                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
//                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
//
//                this.getOnNetworkChangeListener().onNetWorkDisConnect();
//
//                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
//
//                    this.getOnNetworkChangeListener().onNetWorkConnect();
//                }
                Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (null != parcelableExtra) {
                    NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
                    NetworkInfo.State state = networkInfo.getState();
                    boolean isConnected = state== NetworkInfo.State.CONNECTED;//已经连接的状态
                    boolean isDisconnected=state== NetworkInfo.State.DISCONNECTED;//未连接的状态
                    if(isConnected){
                        this.getOnNetworkChangeListener().onNetWorkConnect();
                    }
                    if(isDisconnected && !networkInfo.isAvailable()){
                        this.getOnNetworkChangeListener().onNetWorkDisConnect();
                    }
                }
            }
        }

            /*判断wifi是否开启*/
            /*if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
                    if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
                        Toast.makeText(context, "系统关闭wifi", Toast.LENGTH_SHORT).show();
                    } else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
                        Toast.makeText(context,"系统开启wifi",Toast.LENGTH_SHORT).show();
//                    if(this.isParent) {
//                        for (WifiAdmin wifi : wifiList) {
//                            if(!this.equals(wifi) && wifi.getOnNetworkChangeListener()!=null){
//                                wifi.getOnNetworkChangeListener().onNetWorkDisConnect();
//                            }
//                        }
//                    }
                }
            }*/
    }
}

